package cz.hanis.android.geography.activities;

import java.util.List;

import cz.hanis.android.geography.GeographyApplication;
import cz.hanis.android.geography.R;
import cz.hanis.android.geography.TestActivity;
import cz.hanis.android.geography.TimeTestActivity;
import cz.hanis.android.geography.WrongResourceException;
import cz.hanis.android.geography.models.Country;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class CountryFlagTestTimeActivity extends TimeTestActivity {	
	
	private static final String TAG = "CountryFlagTestActivity";
	
	private TextView tvCountry;		
	private int correct;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTestLayout(R.layout.country_flag_test);		
		setQuestion(getString(R.string.tv_country_flag_question));		
		tvCountry = (TextView) findViewById(R.id.tv_country_flag_country);
		setQuestionView(tvCountry);
		addAnswerView((ImageView) findViewById(R.id.iv_country_flag_flag_1));
		addAnswerView((ImageView) findViewById(R.id.iv_country_flag_flag_2));
		addAnswerView((ImageView) findViewById(R.id.iv_country_flag_flag_3));
		addAnswerView((ImageView) findViewById(R.id.iv_country_flag_flag_4));
		setListeners();

		newRound();
	}
	
	private void setListeners() {
		int i=0;
		for(View view : getAnswerViews()) {
			final int index = i++;
			view.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					answer(index);
				}
			});
		}
	}
	
	@Override
	protected int onAnswer(int answer) {
		int result = ANSWERE_NONE;
		setBackgroudButton(correct, R.drawable.button_9patch_green);		
		if (answer == correct) {
			result = ANSWERE_CORRECT;
		} else if (answer == ANSWERE_TIMED_OUT) {
			result = ANSWERE_TIMED_OUT;
		} else {
			setBackgroudButton(answer, R.drawable.button_9patch_red);
			result = ANSWERE_INCORRECT;
		}
		return result;				
	}
	
	private void setBackgroudButton(int number, int background) {
			getAnswerViews().get(number).setBackgroundResource(background);
	}	
	
	
	@Override
	protected void onNewRound() {			
		for (int i = 0; i < getNumberOfAnswers(); i++) {
			setBackgroudButton(i, R.drawable.button_9patch_grey);
		}

		List<Country> randomCountries = getTools().getRandomCountries(getNumberOfAnswers(),
				getTest().getContinent());
		correct = getTools().getRandom(getNumberOfAnswers());
		String name = randomCountries.get(correct).getName();
		tvCountry.setText(name);
		
		for(int i=0; i < getNumberOfAnswers(); i++) {
			setFlagImage(i, randomCountries.get(i));
		}
	}
	
	private void setFlagImage(int index, Country country) {
		ImageView flag = (ImageView) getAnswerViews().get(index);
		try {
			flag.setImageDrawable(GeographyApplication.getInstance().getFlagDrawable(country.getId()));
		} catch (WrongResourceException e) {
			Log.d(TAG, e.getMessage());
	    }
	}
	
}
